//
//  HBWPlaceholderTextView.m
//  HBW
//
//  Created by Mac on 16/3/14.
//  Copyright © 2016年 mac. All rights reserved.
//

#import "HBWPlaceholderTextView.h"

static CGFloat leftMargin = 5;
static CGFloat topMargin = 5;
//

@implementation HBWPlaceholderTextView

// 代码
- (instancetype)initWithFrame:(CGRect)frame{
    self = [super initWithFrame:frame];
    if (self) {
        
        [self configDefault];
    }
    return self;
}

// XIB
- (instancetype)initWithCoder:(NSCoder *)aDecoder{
    if (self = [super initWithCoder:aDecoder]) {
        
        [self configDefault];
    }
    return self;
}

- (void)configDefault{
    
    if (!self.font) {
        self.font = [UIFont systemFontOfSize:15];
    }
    self.placeholderColor = [UIColor grayColor];
    
    self.layer.borderColor = [UIColor grayColor].CGColor;
    self.layer.borderWidth = 0.5f;
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(textChange:) name:UITextViewTextDidChangeNotification object:self];
}

- (void)drawRect:(CGRect)rect {
    [super drawRect:rect];
    if (self.placeholderColor && self.text.length == 0 && self.placeholder) {
        NSMutableParagraphStyle *paragraph = [[NSMutableParagraphStyle alloc] init];
        paragraph.alignment = self.textAlignment;
        
        
        CGFloat x = leftMargin + self.contentInset.left;
        CGFloat y = topMargin + self.contentInset.top;
        CGFloat width =  self.width - self.contentInset.left - self.contentInset.right - leftMargin;
        CGFloat height =self.height - topMargin - self.contentInset.bottom- self.contentInset.top;
        // 绘制文字
        [self.placeholder drawInRect:CGRectMake(x, y, width, height) withAttributes:@{NSFontAttributeName:self.font, NSForegroundColorAttributeName: self.placeholderColor, NSParagraphStyleAttributeName:paragraph}];
    }
}

- (void)dealloc{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}


- (void)textChange:(NSNotification *)noti{
    if (noti.object == self) {
        [self setNeedsDisplay];
    }
}

- (void)setText:(NSString *)text{
    [super setText:text];
    [self setNeedsDisplay];
}

- (void)setPlaceholder:(NSString *)placeholder{
    _placeholder = placeholder;
    [self setNeedsDisplay];
}

- (void)setPlaceholderColor:(UIColor *)placeholderColor{
    _placeholderColor = placeholderColor;
    [self setNeedsDisplay];
}

- (void)setFont:(UIFont *)font{
    [super setFont:font];
    [self setNeedsDisplay];
}
@end
